import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Spin } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import router from 'umi/router';
import { NumberDivide, DateDiff, FormatnumberZero, Mover, DateStamp } from '@/function.js';

import Highlighter from 'react-highlight-words';

// import * as XLSX from 'xlsx-style';
import {
  Switch,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Table,
  Popconfirm,
} from 'antd';
import XLSX from '../../assets/xlsx.min';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './Test.less';

moment.locale('zh-cn');
// import TableForm from './TableForm';
const listernerable = false;
let nowFormData = '今日';
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['default', 'processing', 'success', 'error'];

/* eslint react/no-multi-comp:0 */
// @connect(({ monitor, loading }) => ({
//   monitor,
//   loading: loading.models.ruleTest,
// }))

@Form.create()
// @connect(({ form1, loading }) => ({
//   form1,
//   submitting: loading.effects['form/submitAdvancedForm'],
// }))
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        id: props.values.id,
        type: props.values.type || 0,
        code: props.values.code,
        openpotential: props.values.openpotential,
        turnovertime: props.values.turnovertime,
        marketprice: props.values.marketprice,
        stikeprice: props.values.stikeprice,
        expiration: props.values.expiration,
        dayexp: props.values.dayexp,
        premium: props.values.premium,
        contracts: props.values.contracts,

        totalpremium: props.values.totalpremium,
        annualized: props.values.annualized,
        annualized2: props.values.annualized2,
        discount: props.values.discount,
        validity: props.values.validity,
        uploader: props.values.uploader,
        turnflag: props.values.turnflag,
      },
      currentStep: 0,
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleAddOrUpdate = currentStep => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      fieldsValue.expiration = fieldsValue.expiration.format('YYYY-MM-DD');
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          handleUpdate(formVals);
          // console.log()
        }
      );
    });
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible, values } = this.props;

    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="submit" type="primary" onClick={() => this.handleAddOrUpdate(currentStep)}>
        提交修改
      </Button>,
    ];
  };

  renderContent = formVals => {
    const { form } = this.props;
    console.log(this.props);
    // var formatTime = (timeStr) => {
    //   console.log(timeStr, typeof timeStr)
    //   if (typeof timeStr == 'string') {
    //     var nowyear = new Date().getFullYear() + '';
    //     return (nowyear + (timeStr.replace(/[\u4e00-\u9fa5]/g, '')));
    //   }
    // }

    return [
      <FormItem key="type" {...this.formLayout} label="类型">
        {form.getFieldDecorator('type', {
          initialValue: { 1: 'Sell Call', 0: 'Sell Put', 2: 'Buy Put', 3: 'Buy Call' }[
            `${formVals.type}`
          ],
          // initialValue: formVals.type,
          rules: [{ required: true, message: '请输入类型！' }],
        })(
          <Select style={{ width: '100%' }} placeholder="请选择类型">
            <Option value="1">Sell Call</Option>
            <Option value="0">Sell Put</Option>
            <Option value="2">Buy Put</Option>
            <Option value="3">Buy Call</Option>
          </Select>
        )}
      </FormItem>,
      <FormItem key="code" {...this.formLayout} label="股票代码">
        {form.getFieldDecorator('code', {
          rules: [{ required: true, message: '请输入股票代码！' }],
          initialValue: formVals.code,
        })(<Input placeholder="请输入股票代码" />)}
      </FormItem>,
      <FormItem key="stikeprice" {...this.formLayout} label="执行价格">
        {form.getFieldDecorator('stikeprice', {
          rules: [
            { required: true, message: '请输入执行价格' },
            {
              pattern: /^(\d+)((?:\.\d+)?)$/,
              message: '请输入合法金额数字',
            },
          ],
          initialValue: formVals.stikeprice,
        })(<Input placeholder="请输入 执行价格" prefix="$" />)}
      </FormItem>,
      <FormItem key="expiration" {...this.formLayout} label="到期日">
        {form.getFieldDecorator('expiration', {
          rules: [{ required: true, message: '请输入到期日！' }],
          initialValue: formVals.expiration ? moment(formVals.expiration, 'YYYY/MM/DD') : '',
        })(<DatePicker />)}
      </FormItem>,

      <FormItem key="premium" {...this.formLayout} label="权利金">
        {form.getFieldDecorator('premium', {
          rules: [
            { required: true, message: '请输入权利金！' },
            {
              pattern: /^(\d+)((?:\.\d+)?)$/,
              message: '请输入合法金额数字',
            },
          ],
          initialValue: formVals.premium,
        })(<Input placeholder="请输入权利金" prefix="$" />)}
      </FormItem>,
      <FormItem key="contracts" {...this.formLayout} label="最多合约数">
        {form.getFieldDecorator('contracts', {
          rules: [
            { required: true, message: '请输入最多合约数！' },
            {
              pattern: /^(\d+)((?:\.\d+)?)$/,
              message: '请输入数字',
            },
          ],
          initialValue: formVals.contracts,
        })(<Input placeholder="请输入最多合约数" />)}
      </FormItem>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { currentStep, formVals } = this.state;
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="修改信息"
        visible={updateModalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}
@connect(({ monitor, loading }) => ({
  monitor,
  submitting: loading.effects['form/submitAdvancedForm'],
}))
class Options extends PureComponent {
  index = 0;

  cacheOriginData = {};

  state = {
    isupdate: false,
    dateList: ['今日'],
    filterData: [],
    expandForm: false, // 查询菜单栏 是否显示
    listLoading: false,
    formValues: {
      method: 'GetList',
      page: 1,
      pagesize: 200,
      type: 3,
      name: '',
    }, // 查询菜单栏   查询参数
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    stepFormValues: {},
    searchText: '', // table列的搜索文本
    autoRefrsh: true,
    currentDataSource: [],
    openSumYes: 0,
    openSumNo: 0,
    filteredInfo: null,
  };

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          确定
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text}
      />
    ),
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  // 默认加载数据-起始方法
  render() {
    const {
      monitor: { data },
      loading,
      total,
    } = this.props;
    const {
      dateList,
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      selectItem,
      listLoading,
      currentDataSource,
    } = this.state;
    // console.log(data, 'data.data')
    this.state.data = data.data;

    const children = [];
    if (dateList.length > 0) {
      for (let i = 0; i < dateList.length; i++) {
        children.push(
          <Option key={!dateList[i] ? ' ' : dateList[i].substring(0, 10)}>
            {!dateList[i] ? ' ' : dateList[i].substring(0, 10)}
          </Option>
        );
      }
    }
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};
    const columns = [
      // {
      //   title: '',
      //   dataIndex: 'id',
      //   render: text => <span>{}</span>,
      // },
      {
        title: '类型',
        dataIndex: 'type',
        editable: true,
        width: 100,
        align: 'center',
        filters: [
          {
            text: 'Sell Call',
            value: 1,
          },
          {
            text: 'Sell Put',
            value: 0,
          },
          {
            text: 'Buy Put',
            value: 2,
          },
          {
            text: 'Buy Call',
            value: 3,
          },
        ],
        filteredValue: filteredInfo.type || null,
        onFilter: (value, record) => {
          if (record.type != undefined) {
            return record.type === value;
          }
        },
        render: text => (
          <span>{{ 1: 'Sell Call', 0: 'Sell Put', 2: 'Buy Put', 3: 'Buy Call' }[text]}</span>
        ),
      },
      {
        title: '源',
        dataIndex: 'trading',
        width: 80,
        align: 'center',
        filteredValue: filteredInfo.trading || null,
        render: text => <span>{text == 1 ? '富途' : ' 路透'}</span>,
        filters: [
          {
            text: '富途',
            value: 1,
          },
          {
            text: '路透',
            value: 0,
          },
        ],
        onFilter: (value, record) => {
          if (record.trading != undefined) {
            return record.trading === value;
          }
        },
      },
      {
        title: '股票代码',
        dataIndex: 'code',
        width: 80,
        align: 'center',
        // filteredValue: filteredInfo.code || null,
        ...this.getColumnSearchProps('code'),
      },
      {
        title: '到期日',
        width: 120,
        align: 'center',
        dataIndex: 'expiration',
        render: (text, record) => {
          if (text) return text.substring(0, 10);
        },
        sorter: (a, b) => DateStamp(a.expiration) - DateStamp(b.expiration),
      },
      {
        title: '订单有效期',
        dataIndex: 'date',
        width: 120,
        align: 'center',
        render: (text, record) => {
          if (text) return text.substring(0, 10);
        },
        sorter: (a, b) => DateStamp(a.date) - DateStamp(b.date),
      },
      {
        title: '执行价',
        width: 80,
        dataIndex: 'stikeprice',
        align: 'center',
        render: text => <span>{text ? `$${text}` : ' '}</span>,
        sorter: (a, b) => a.stikeprice - b.stikeprice,
      },
      {
        title: '权利金',
        width: 80,
        dataIndex: 'premium',
        align: 'center',
        render: text => <span>{text ? `$${text}` : ' '}</span>,
        sorter: (a, b) => a.premium - b.premium,
      },
      {
        title: '最多合约数',
        width: 100,
        dataIndex: 'contracts',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.contracts - b.contracts,
      },
      {
        title: '买价',
        width: 80,
        dataIndex: 'bidprice',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.bidprice - b.bidprice,
      },
      {
        title: '卖价',
        width: 80,
        dataIndex: 'askprice',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.askprice - b.askprice,
      },

      {
        title: '最新价',
        width: 80,
        dataIndex: 'cflast',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.cflast - b.cflast,
      },
      {
        title: '成交量',
        width: 80,
        dataIndex: 'vol',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.vol - b.vol,
      },
      // {
      //   title: '最高价',
      //   width: 80,
      //   dataIndex: 'high',
      //   render: text => <span>{text ? text : ' '}</span>,
      //   sorter: (a, b) => a.high - b.high,
      // },
      // {
      //   title: '最低价',
      //   width: 80,
      //   dataIndex: 'low',
      //   render: text => <span>{text ? text : ' '}</span>, sorter: (a, b) => a.low - b.low,
      // },
      {
        title: '分析',
        width: 80,
        dataIndex: 'turnflag',
        align: 'center',
        render: text => <span>{text ? '成交' : ' '}</span>,
        filteredValue: filteredInfo.turnflag || null,
        filters: [
          {
            text: '成交',
            value: true,
          },
          {
            text: '未成交',
            value: false,
          },
        ],
        onFilter: (value, record) => {
          if (record.turnflag != undefined) {
            return record.turnflag === value;
          }
        },
      },
      {
        title: '成交时间',
        width: 120,
        dataIndex: 'turnovertime',
        align: 'center',
        render: (text, record) => {
          if (text) return text.substring(10, 20);
        },
        sorter: (a, b) => a.turnovertime - b.turnovertime,
      },
      {
        title: '操作',
        width: 120,
        align: 'center',
        render: (text, record) => {
          if (record.type != 0 && !record.type) {
            return null;
          }
          return (
            <Fragment>
              <Popconfirm
                title="是否要删除此条？"
                onConfirm={() => this.handleRemoveModalVisible(record)}
              >
                <a style={{ marginRight: '4px' }}>删除</a>
              </Popconfirm>
              <Divider type="vertical" />
              <a onClick={() => this.handleUpdateModalVisible(true, record, true)}>更改</a>
            </Fragment>
          );
        },
      },
      {
        title: '敞口',
        dataIndex: 'openpotential',
        width: 100,
        align: 'center',
        render: text => <span>{text ? `$${text}` : ' '}</span>,
        sorter: (a, b) => a.openpotential - b.openpotential,
      },

      {
        title: '市场价格',
        width: 100,
        dataIndex: 'marketprice',
        align: 'center',
        render: text => <span>{text ? `$${text}` : ' '}</span>,
        sorter: (a, b) => a.marketprice - b.marketprice,
      },

      {
        title: '到期日天数',
        width: 100,
        dataIndex: 'dayleft',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.dayleft - b.dayleft,
      },

      {
        title: '最多合约数',
        width: 100,
        dataIndex: 'contracts',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.contracts - b.contracts,
      },
      {
        title: '权利金总额',
        width: 100,
        dataIndex: 'totalpremium',
        align: 'center',
        render: text => <span>{text ? `$${text}` : ' '}</span>,
        sorter: (a, b) => a.totalpremium - b.totalpremium,
      },
      {
        title: '年回收(扣佣）',
        width: 100,
        dataIndex: 'annualized',
        align: 'center',
        render: text => <span>{text ? `${mul(text, 100)}%` : ' '}</span>,
        sorter: (a, b) => a.annualized - b.annualized,
      },
      {
        title: '年回收',
        width: 80,
        dataIndex: 'annualized2',
        align: 'center',
        render: text => <span>{text ? `${mul(text, 100)}%` : ' '}</span>,
        sorter: (a, b) => a.annualized2 - b.annualized2,
      },

      {
        title: '折扣',
        width: 80,
        dataIndex: 'discount',
        align: 'center',
        render: text => <span>{text || ' '}</span>,
        sorter: (a, b) => a.discount - b.discount,
      },

      {
        title: '归属人',
        align: 'center',
        filteredValue: filteredInfo.name || null,
        filters: [
          {
            text: '花旗',
            value: '花旗',
          },
        ],
        onFilter: (value, record) => {
          if (record.name != undefined) {
            return record.name === value;
          }
        },
        // width: 100,
        dataIndex: 'name',
        render: text => <span>{text || ' '}</span>,
      },
    ];
    return (
      <PageHeaderWrapper title="美股期权成交监控列表">
        <div
          style={{
            display: 'flex',
            backgroundColor: '#fff',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <div className={styles.controlBar}>
            <div
              style={{
                display: 'flex',
                flexFlow: 'row wrap',
                alignContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <Button type="primary" className={styles.optionsbutton} onClick={this.optionsUpload}>
                上传
              </Button>
              <input className="fileipt" type="file" />
              <Button onClick={this.optionsClear}>清空</Button>
              <Button
                icon="plus"
                type="primary"
                onClick={() => this.handleUpdateModalVisible(true, this.state.formValues)}
              >
                新建
              </Button>
            </div>
            <div
              style={{
                display: 'flex',
                flexFlow: 'row wrap',
                alignContent: 'space-between',
                alignItems: 'center',
                textAlign: 'center',
                justifyContent: 'center',
              }}
            >
              <span
                style={{
                  fontSize: 16,
                  // textAlign: 'left',
                  fontWeight: '600',
                  marginLeft: '1em',
                  marginBottom: '4px',
                  height: '32px',
                  lineHeight: '32px',
                }}
              >
                按日期查询
              </span>
              <Select
                defaultValue="今日"
                style={{ marginLeft: '1em', width: '8em', marginBottom: '4px' }}
                onChange={this.handleChange.bind(this)}
                dropdownMatchSelectWidth={false}
              >
                {children}
              </Select>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', marginRight: '30px' }}>
            <div style={{ marginRight: '10px' }}>自动刷新</div>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              onChange={this.refreshControl.bind(this)}
            />
          </div>
        </div>
        <div style={{ display: 'flex', marginLeft: '25px', marginTop: '14px' }}>
          <div style={{ marginRight: '18px' }}>
            敞口合计:${this.state.openSumYes + this.state.openSumNo}
          </div>

          <div style={{ marginRight: '18px' }}>成交敞口合计:${this.state.openSumYes}</div>

          <div>未成交敞口合计:${this.state.openSumNo}</div>
        </div>
        <Card bordered={false}>
          <div className={styles.tableList}>
            {/*      <div className={styles.tableListForm}>{this.renderForm()}</div> */}

            <Table
              rowKey="id"
              scroll={{ x: 2260, y: 650 }}
              columns={columns}
              dataSource={this.state.data}
              pagination={false}
              rowClassName={this.rowClassName}
              bordered
              onChange={this.tableChabge.bind(this)}
            />
          </div>
        </Card>
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }

  // tableb变化
  tableChabge = (pagination, filters, sorter, extra) => {
    //  alert('tableChabge')
    // console.log(pagination, filters, sorter, extra, 'tableChabge')
    // this.setState({ currentDataSource: extra.currentDataSource })
    let openSumYes = 0;
    let openSumNo = 0;
    for (let i = 0, len = extra.currentDataSource.length; i < len; i++) {
      if (extra.currentDataSource[i].turnflag) {
        openSumYes += extra.currentDataSource[i].openpotential
          ? extra.currentDataSource[i].openpotential * 1
          : 0;
      } else {
        openSumNo += extra.currentDataSource[i].openpotential
          ? extra.currentDataSource[i].openpotential * 1
          : 0;
      }
    }
    // alert(openTotel)
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter,
      openSumYes,
      openSumNo,
    });

    // this.state.openTotel = openTotel
  };

  handleUpdateModalVisible = (flag, record, isupdate) => {
    if (isupdate) {
      this.setState({
        isupdate: true,
      });
    }
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  handleRemoveModalVisible = record => {
    const that = this;
    const { data } = this.state;
    const { onChange } = this.props;
    // const newData = data.filter(item => item.id !== key);
    const { dispatch } = this.props;
    dispatch({
      type: 'monitor/Delete',
      payload: {
        id: record.id,
      },
      callback: res => {
        if (res.code == 1) {
          message.success('删除成功!');
          dispatch({
            type: 'monitor/GetByDate',
            payload: {
              date: nowFormData,
            },
            callback: res => {
              that.setState({
                openSumYes: res.openSumYes,
                openSumNo: res.openSumNo,
              });
            },
          });
        }
      },
    });
    // this.setState({ data: newData });
    // onChange(newData);
  };

  handleUpdate = fields => {
    console.log(fields, 'ffieldsfieldsfieldsfieldsfieldsields');
    const that = this;
    console.log(this.state.isupdate);
    const { dispatch } = this.props;
    const { formValues, isupdate } = this.state;
    console.log(fields, 'fields');
    // var turnovertime=fields.turnovertime+'';

    if (fields.type == 'Sell Call') {
      fields.type = 1;
    } else if (fields.type == 'Sell Put') {
      fields.type = 0;
    } else if (fields.type == 'Buy Put') {
      fields.type = 2;
    } else if (fields.type == 'Buy Call') {
      fields.type = 3;
    }

    if (!isupdate) {
      dispatch({
        type: 'monitor/AddNewOption',
        payload: fields,
        callback: () => {
          message.success('成功!');
          this.handleUpdateModalVisible();
          dispatch({
            type: 'monitor/TurnOverMonitorList',
            payload: {
              date: '今日',
              callback: res => {
                that.setState({
                  openSumYes: res.openSumYes,
                  openSumNo: res.openSumNo,
                });
              },
            },
          });
        },
      });
    } else {
      dispatch({
        type: 'monitor/tradingUpdateOption',
        payload: fields,
        callback: () => {
          message.success('成功!');
          this.handleUpdateModalVisible();
          dispatch({
            type: 'monitor/TurnOverMonitorList',
            payload: {
              date: '今日',
              callback: res => {
                that.setState({
                  openSumYes: res.openSumYes,
                  openSumNo: res.openSumNo,
                });
              },
            },
          });
        },
      });
    }
  };

  refreshControl = (checked, ev) => {
    const that = this;
    // console.log(checked, 'checked')
    // this.setState({ autoRefrsh: checked })
    if (checked) {
      window.refreshTimer = setInterval(() => {
        const { dispatch } = that.props;
        const { formValues } = that.state;
        dispatch({
          type: 'monitor/GetByDate',
          payload: {
            date: nowFormData,
          },
          callback: res => {
            that.setState({
              openSumYes: res.openSumYes,
              openSumNo: res.openSumNo,
            });
          },
        });
      }, 5000);
    } else {
      clearInterval(window.refreshTimer);
    }
  };

  handleChange = value => {
    // this.setState({ filteredInfo: null });
    const that = this;
    console.log(value);
    const { dispatch } = this.props;
    const { formValues } = this.state;
    // value = value.replace(/[^0-9\.]/gi, '');
    // value = value.slice(0, 2) + '-' + value.slice(2);
    nowFormData = value;
    const data = {
      date: value,
    };
    if (value == '今日') {
      //  this.componentDidUpdate();
    }
    dispatch({
      type: 'monitor/GetByDate',
      payload: data,
      callback: res => {
        that.setState({
          openSumYes: res.openSumYes,
          openSumNo: res.openSumNo,
          filteredInfo: null,
        });
      },
    });
  };

  rowClassName = (record, index) => {
    // return Object.keys(record).length < 5 || record.turnflag ? styles.staticRow : '';
    if (Object.keys(record).length < 5) return styles.staticRow;
    if (record.turnflag) return styles.dealRow;
  };

  optionsClear = () => {
    const that = this;
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'monitor/clear',
      payload: formValues,
      callback: res => {
        message.success('清空成功!');
        that.componentDidMount();
      },
    });
  };

  optionsUpload = () => {
    const that = this;
    document.querySelector('.fileipt').click();
    const $fileipt = document.querySelector('.fileipt');
    if ($fileipt.getAttribute('change') !== '1') {
      $fileipt.setAttribute('change', '1');
      $fileipt.addEventListener('change', uploadExcel);
    }
    function uploadExcel() {
      if (!this.files) {
        return;
      }
      const f = this.files[0];
      parseXLSX(f, function(carData) {
        console.log(carData, 'carData');
        const mapobj = [];
        const submitData = [];
        let iscollected = false;
        for (let i = 0, le = carData.length; i < le; i++) {
          const len = Object.keys(carData[i]).length;
          if (len >= 10 && !iscollected) {
            iscollected = true;
            for (const j in carData[i]) {
              if (carData[i][j].match(/股票代/)) {
                mapobj.code = j;
              } else if (carData[i][j].match(/合约数/)) {
                mapobj.contracts = j;
              } else if (carData[i][j].match(/expiration/i)) {
                mapobj.expiration = j;
              } else if (carData[i][j].match(/权利金 /)) {
                mapobj.premium = j;
              } else if (carData[i][j].match(/执行价格/)) {
                mapobj.stikeprice = j;
              } else if (carData[i][j].match(/归属/)) {
                mapobj.uploader = j;
              } else if (carData[i][j].match(/订单有效期/)) {
                mapobj.orderExpiry = j;
              }
            }
          } else if (len >= 10 && iscollected) {
            const submitDataItem = {};
            submitDataItem.type = 0;
            const { code } = mapobj;
            const { contracts } = mapobj;

            const { expiration } = mapobj;
            const { premium } = mapobj;
            const { stikeprice } = mapobj;
            const { type } = mapobj;
            const { uploader } = mapobj;
            const { orderExpiry } = mapobj;

            submitDataItem.code = carData[i][code] || '';
            submitDataItem.contracts = carData[i][contracts] || '';
            console.log(carData[i][expiration]);
            submitDataItem.expiration = formatDate(carData[i][expiration]) || '';

            submitDataItem.premium = carData[i][premium].toFixed(2) || '';
            submitDataItem.stikeprice = carData[i][stikeprice] || '';
            submitDataItem.orderExpiry = formatDate(carData[i][orderExpiry]) || '';
            submitDataItem.uploader = carData[i][uploader] || '';

            for (const k in carData[i]) {
              if (`${carData[i][k]}`.match(/Sell Call/i)) {
                submitDataItem.type = 1;
              } else if (`${carData[i][k]}`.match(/Buy Put/i)) {
                submitDataItem.type = 2;
              } else if (`${carData[i][k]}`.match(/Buy Call/i)) {
                submitDataItem.type = 3;
              }
            }
            submitData.push(submitDataItem);
          }
        }
        const { dispatch } = that.props;
        const { formValues } = that.state;

        dispatch({
          type: 'monitor/Upload',
          payload: submitData,
          callback: res => {
            $fileipt.value = '';
            message.success('上传成功!');
            dispatch({
              type: 'monitor/TurnOverMonitorList',
              payload: { date: '今日' },
              callback: res => {
                that.setState({
                  openSumYes: res.openSumYes,
                  openSumNo: res.openSumNo,
                });
              },
            });
            this.setState({
              listLoading: false,
            });
          },
        });
        console.log(submitData, 'submitData');
      });
      function format(carData) {
        const obj = {};
        const reg = /(\ )|(\")|(\')|(\r)|(\n)|(\,)/g;
        for (let i = 0, len = carData.length; i < len; i++) {
          for (j in carData[i]) {
            if (!obj[j]) {
              obj[j] = [];
            }
            obj[j].push(carData[i][j].replace(reg, ''));
          }
        }
        obj.userId = localStorage.getItem('userid');
        return obj;
      }
      function formatDate(numb) {
        // console.log(numb, 'numbnumb')

        const time = new Date((numb - 1) * 24 * 3600000 + 1);
        time.setYear(time.getFullYear() - 70);
        const year = time.getFullYear();
        const month = time.getMonth() + 1;
        const date = time.getDate();
        return `${year}-${month < 10 ? `0${month}` : month}-${date < 10 ? `0${date}` : date}`;
      }
    }

    function parseXLSX(f, cb) {
      let carData;
      let wb; // 读取完成的数据
      const rABS = false; // 是否将文件读取为二进制字符串
      const reader = new FileReader();
      reader.onload = function(e) {
        const data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {
            type: 'base64',
          });
        } else {
          wb = XLSX.read(data, {
            type: 'binary',
          });
        }
        // carData就是需要的JSON数据
        console.log(wb, 'wb');
        carData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

        typeof cb === 'function' && cb(carData);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
      function fixdata(data) {
        // 文件流转BinaryString
        let o = '';
        let l = 0;
        const w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
      }
    }
  };

  componentWillMount() {
    // var that = this;
    // const { dispatch } = this.props;
    // const { formValues } = this.state;
    // dispatch({
    //   type: 'monitor/GetDateList',
    //   callback: res => {
    //     if (res.code == 1) {
    //       that.setState({
    //         dateList: ['今日'].concat(res.data),
    //       });
    //     }
    //   },
    // });
  }

  componentDidMount() {
    const that = this;
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'monitor/GetDateList',
      callback: res => {
        if (res.code == 1) {
          that.setState({
            dateList: ['今日'].concat(res.data),
          });
        }
      },
    });
    dispatch({
      type: 'monitor/TurnOverMonitorList',
      payload: { date: '今日' },
      callback: res => {
        that.setState({
          openSumYes: res.openSumYes,
          openSumNo: res.openSumNo,
        });
      },
    });
  }
}
function mul(arg1, arg2) {
  if (!arg1 || !arg2) return;
  let m = 0;
  const s1 = arg1.toString();
  const s2 = arg2.toString();
  try {
    m += s1.split('.')[1].length;
  } catch (e) {}
  try {
    m += s2.split('.')[1].length;
  } catch (e) {}
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}
export default Options;
